package shengsiyuan.thread;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author song
 * @date 2023/3/24 11:59
 */
public class CompletableFutureDemo {
    public static void main(String[] args) {
        CompletableFutureDemo completableFutureDemo = new CompletableFutureDemo();
        List<String> price = completableFutureDemo.price();
        System.out.println(price);
    }

    private static final Executor EXECUTOR = new ThreadPoolExecutor(10, 100, 100, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(100), (ThreadFactory) Thread::new);

    private List<String> price() {


        List<String> stringList = Collections.synchronizedList(new ArrayList<>(4));

        CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> la(1), EXECUTOR);
        CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> la(2), EXECUTOR);
        CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> la(3), EXECUTOR);

        try {
            stringList.add(task1.get(1, TimeUnit.MILLISECONDS));
            stringList.add(task2.get(1, TimeUnit.MILLISECONDS));
            stringList.add(task3.get(1, TimeUnit.MILLISECONDS));
        } catch (Exception exception) {
            System.out.println("bbbbbbbbbbbbbbbbbbbbbb");
        }

        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(task1, task2, task3).whenComplete((i, j) -> {
            if (null != i) {
                stringList.add(i.toString());
            }
        });

        try {
            voidCompletableFuture.get(2, TimeUnit.SECONDS);
        } catch (Exception exception) {
            System.out.println("==== error");
        }
        return stringList;
    }

    public String la(Integer integer) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return integer + ",,,,,,";
    }
}
